package com.tarena.lbs.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.mapper.StoreChainMapper;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.dao.repository.StoreChainRepository;
import com.tarena.lbs.business.pojo.po.StoreChainPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.StoreChainQuery;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.pojo.vo.StoreChainVO;
import com.tarena.lbs.business.service.BusinessService;
import com.tarena.lbs.business.service.StoreChainService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.stream.Collectors;

@Repository
public class StoreChainServiceImpl implements StoreChainService {
    @Autowired
    private StoreChainRepository storeChainRepository;
    @Autowired
    private StoreChainMapper storeChainMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private BusinessService businessService;
    @Override
    public PageResult<StoreChainVO> pageList(StoreChainQuery query) {
        // 设置分页参数
        if (query.getPageNo() != null && query.getPageSize() != null) {
            PageHelper.startPage(query.getPageNo(), query.getPageSize());
        } else {
            // 提供默认分页参数，防止null导致的问题
            PageHelper.startPage(1, 10);
        }

        // 构建查询条件
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<StoreChainPO> queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        // 按商家ID筛选
        if (query.getBusinessId() != null) {
            queryWrapper.eq("business_id", query.getBusinessId());
        }
        // 按店铺ID筛选
        if (query.getStoreId() != null) {
            queryWrapper.eq("store_id", query.getStoreId());
        }
        // 按链接状态筛选
        if (query.getLinkStatus() != null) {
            queryWrapper.eq("link_status", query.getLinkStatus());
        }
        // 执行查询
        List<StoreChainPO> poList = storeChainMapper.selectList(queryWrapper);
        // 转换PO为VO
        List<StoreChainVO> voList = new ArrayList<>();
        // 批量查询店铺信息，提高性能
        if (!poList.isEmpty()) {
            // 获取所有店铺ID
            List<Integer> storeIds = poList.stream()
                    .map(StoreChainPO::getStoreId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 批量查询店铺信息
            List<StorePO> storePOs = storeMapper.selectBatchIds(storeIds);

            // 转换为Map，方便快速查找
            Map<Integer, StorePO> storeMap = storePOs.stream()
                    .collect(Collectors.toMap(StorePO::getId, storePO -> storePO));
            // 获取所有商家ID
            List<Integer> businessIds = poList.stream()
                    .map(StoreChainPO::getBusinessId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            // 批量查询商家信息
            Map<Integer, String> businessNameMap = new HashMap<>();
            for (Integer businessId : businessIds) {
                BusinessVO businessVO = businessService.getBusinessById(businessId);
                if (businessVO != null) {
                    businessNameMap.put(businessId, businessVO.getBusinessName());
                }
            }
            // 填充VO对象
            for (StoreChainPO po : poList) {
                StoreChainVO vo = new StoreChainVO();
                BeanUtils.copyProperties(po, vo);

                // 填充店铺信息
                if (po.getStoreId() != null && storeMap.containsKey(po.getStoreId())) {
                    StorePO storePO = storeMap.get(po.getStoreId());
                    // 添加字段判空处理，设置默认值
                    vo.setStoreName(storePO.getStoreName() != null ? storePO.getStoreName() : "");
                    vo.setStoreLocation(storePO.getStoreLocation() != null ? storePO.getStoreLocation() : "");

                    // 可以根据需要添加更多店铺字段
                } else {
                    // 如果没有找到对应的店铺信息，设置默认空字符串
                    vo.setStoreName("");
                    vo.setStoreLocation("");

                } // 填充商家名称
                if (po.getBusinessId() != null && businessNameMap.containsKey(po.getBusinessId())) {
                    vo.setBusinessName(businessNameMap.get(po.getBusinessId()));
                } else {
                    vo.setBusinessName(""); // 设置默认空字符串
                }

                voList.add(vo);
            }
        }

        // 构建分页结果
        PageResult<StoreChainVO> pageResult = new PageResult<>();
        pageResult.setObjects(voList);
        pageResult.setPageNo(query.getPageNo() != null ? query.getPageNo() : 1);
        pageResult.setPageSize(query.getPageSize() != null ? query.getPageSize() : 10);

        // 获取总数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<StoreChainPO> countWrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        if (query.getBusinessId() != null) countWrapper.eq("business_id", query.getBusinessId());
        if (query.getStoreId() != null) countWrapper.eq("store_id", query.getStoreId());
        if (query.getLinkStatus() != null) countWrapper.eq("link_status", query.getLinkStatus());

        long total = storeChainMapper.selectCount(countWrapper);
        pageResult.setTotal(total);

        return pageResult;
    }
    @Override
    public void enableQRCode(Integer id) {
        storeChainRepository.updateStatus(id, 0); // 0表示启用
    }

    @Override
    public void disableQRCode(Integer id) {
        storeChainRepository.updateStatus(id, -1); // -1表示禁用
    }
}
